package com.yenlien.traceyun.control.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.common.bean.UserInfo;
import com.yenlien.traceyun.control.bean.RestURL;
import com.yenlien.traceyun.control.dao.LogDao;
import com.yenlien.traceyun.control.entity.Log;
import com.yenlien.traceyun.control.interceptor.UserAuthUtil;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LogService {

    @Autowired
    private LogDao logDao;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 添加日志记录
     *
     * @param operation
     * @param profession
     */
    public void put(String operation, String profession) {
        Log log = new Log();
        String username = UserAuthUtil.getLoginUser().getUsername();
        String companyId = UserAuthUtil.getLoginUser().getCompanyId();
        if (StringUtils.isEmpty(username)) {
            throw new BusinessException("操作人员不存在");
        }
        String ip = request.getRemoteAddr();
        if (StringUtils.isEmpty(ip)) {
            throw new BusinessException("ip地址错误");
        }
        log.setCompanyId(companyId);
        log.setUserName(username);
        log.setCreatetime(new Date());
        log.setIp(ip);
        log.setOperation(operation);
        log.setProfession(profession);
        logDao.save(log);
    }

    /**
     * 查询日志
     *
     * @param page
     * @return
     */
    public Page<Log> select(Integer page) {
        Sort ageSort = Sort.by(Sort.Direction.DESC, "createtime");
        PageRequest pageRequest = PageRequest.of(page, 10, ageSort);
        Page<Log> all = logDao.findAll(pageRequest);
        return all;
    }

    /**
     * 搜索，返回规定时间类的数据
     *
     * @param log
     */
    public Object search(Log log) {
        Pageable pageable = PageRequest.of(log.getPage(), log.getPageSize(), Sort.Direction.DESC, "createtime");
        return logDao.findAll((Root<Log> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(log.getTime()) && org.apache.commons.lang3.StringUtils.isNotBlank(log.getTimes())) {
                try {
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    Date dateStart = df.parse(log.getTime());
                    Date dateEnd = df.parse(log.getTimes());
                    list.add(cb.between(root.get("createtime"), dateStart, dateEnd));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (!StringUtils.isEmpty(log.getUserName())) {
                list.add(cb.like(root.get("userName"), "%" + log.getUserName() + "%"));
            }
            if (!StringUtils.isEmpty(log.getOperation())) {
                list.add(cb.equal(root.get("operation"), log.getOperation()));
            }
            Predicate[] predicate = new Predicate[list.size()];
            return cb.and(list.toArray(predicate));
        }, pageable);
        // 原逻辑
/*            if (log.getUserName()!=null){
                List<Log> byUserNameAndOperation = logDao.findByUserNameAndOperation(log.getUserName(), log.getOperation());
                for (int i=0; i<byUserNameAndOperation.size();i++){
                    long time1 = byUserNameAndOperation.get(i).getCreatetime().getTime();
                    if (time1>=date.getTime() && time1<=date1.getTime()){
                        logs.add(byUserNameAndOperation.get(i));
                    }
                }
            }
            if (log.getUserName()==null){
                List<Log> byUserNameAndOperation = logDao.findByOperation(log.getOperation());
                for (int i=0; i<byUserNameAndOperation.size();i++){
                    long time1 = byUserNameAndOperation.get(i).getCreatetime().getTime();
                    if (time1>=date.getTime() && time1<=date1.getTime()){
                        logs.add(byUserNameAndOperation.get(i));
                    }
                }
            }*/
    }

    /**
     * 查询所有操作
     *
     * @return
     */
    public Object getOperation() {
        return logDao.findAll().stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Log::getOperation))), ArrayList::new));
    }


    /**
     * 查询30天内的活跃用户
     *
     * @return
     */
    @com.yenlien.traceyun.control.config.Log(operation = "用户登录", profession = "新增登录")
    public int userActivation() {
        // 以前代码无法实现
//        return logDao.findDistinctUserNameByCreatetimeBetween(startDate,date).size();
        // 修正后
        JSONObject jsonObject = new JSONObject();
        UserInfo userInfo = UserAuthUtil.getLoginUser();
        String userType = userInfo.getUserType();
        if (userType.equals("GOV")) {
            jsonObject.put("parentId", userInfo.getCompanyId());
        } else if ("COMMON".equals(userType) || "COMPANY".equals(userType)) {
            jsonObject.put("id", userInfo.getCompanyId());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        ArrayList<String> list = restTemplate.postForObject(RestURL.USERCENTER + "company/getUserNum", new HttpEntity<String>(jsonObject.toJSONString(), headers), ArrayList.class);
        return logDao.getCompActivation(list);
    }

    /**
     * 查询30天内活跃的企业
     *
     * @return
     */
    public int companyActivation() {
//        Date date =new Date();
//        Date startDate = DateUtils.addDays(date, -30);
//        return logDao.findCompanyIdDistinctByCreatetimeBetween(startDate,date).size();
        JSONObject jsonObject = new JSONObject();
        UserInfo userInfo = UserAuthUtil.getLoginUser();
        String userType = userInfo.getUserType();
        if (userType.equals("GOV")) {
            jsonObject.put("parentId", userInfo.getCompanyId());
        } else if ("COMMON".equals(userType) || "COMPANY".equals(userType)) {
            jsonObject.put("id", userInfo.getCompanyId());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        ArrayList<String> list = restTemplate.postForObject(RestURL.USERCENTER + "company/companyNumber", new HttpEntity<String>(jsonObject.toJSONString(), headers), ArrayList.class);
        return logDao.getCompActivation(list);
    }


}
